package com.llsydn.contentResolver;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import com.llsydn.hello.R;

/**
 * @author lilinshen
 * @title ContentResolver
 * @description 请填写相关描述
 * @date 2018/9/30 15:22
 */
public class ContentResolverActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content_resolver);
    }

    /**
     * 插入
     *
     * @param view
     */
    public void insert(View view) {
        //得到ContentResolver对象
        ContentResolver resolver = getContentResolver();

        //调用insert,得到uri
        Uri uri = Uri.parse("content://com.llsydn.contentProvider.PersonProvider/person");
        ContentValues values = new ContentValues();
        values.put("name", "lls");
        Uri insert = resolver.insert(uri, values);

        //取出cursor中的数据，并显示
        Long id = ContentUris.parseId(insert);
        Toast.makeText(this, id + "插入成功", Toast.LENGTH_SHORT).show();

    }

    /**
     * 删除
     *
     * @param view
     */
    public void delete(View view) {
        //得到ContentResolver对象
        ContentResolver resolver = getContentResolver();

        //调用insert,得到uri
        Uri uri = Uri.parse("content://com.llsydn.contentProvider.PersonProvider/person/1");
        int deleteCount = resolver.delete(uri, null, null);
        Toast.makeText(this, "删除成功：" + deleteCount, Toast.LENGTH_SHORT).show();

    }

    /**
     * 更新
     *
     * @param view
     */
    public void update(View view) {
        //得到ContentResolver对象
        ContentResolver resolver = getContentResolver();
        //调用insert,得到uri
        Uri uri = Uri.parse("content://com.llsydn.contentProvider.PersonProvider/person/2");
        ContentValues values = new ContentValues();
        values.put("name", "llsydn");
        int updateCount = resolver.update(uri, values, null, null);
        Toast.makeText(this, "更新成功：" + updateCount, Toast.LENGTH_SHORT).show();
    }

    /**
     * 通过ContentResolver调用ContentProvider查询所有记录
     *
     * @param view
     */
    public void query(View view) {
        //得到ContentResolver对象
        ContentResolver resolver = getContentResolver();

        //调用query,得到cursor
        Uri uri = Uri.parse("content://com.llsydn.contentProvider.PersonProvider/person/2");
        Cursor cursor = resolver.query(uri, null, null, null, null);

        //取出cursor中的数据，并显示
        if (cursor.moveToNext()) {
            int id = cursor.getInt(0);
            String name = cursor.getString(1);
            Toast.makeText(this, id + ":" + name, Toast.LENGTH_SHORT).show();
        }
    }

}
